<template>
  <view class="order-confirm-page">
    <!-- 页面加载状态 -->
    <PageLoading :show="pageLoading" :primary-color="primaryColor" loading-text="加载中..." />
    
    <!-- 页面主要内容 -->
    <view class="page-content" v-show="shouldShowContent">
    <scroll-view class="content-scroll" scroll-y>
      <!-- 收货地址 -->
      <view class="address-section">
        <view class="section-header">
          <text class="section-title">收货地址</text>
          <view class="address-action" @click="selectAddress">
            <text class="action-text">{{ selectedAddress ? '更换地址' : '选择地址' }}</text>
            <text class="action-arrow">›</text>
          </view>
        </view>
        
        <view class="address-card" v-if="selectedAddress">
          <view class="address-info">
            <view class="address-header">
              <text class="recipient-name">{{ selectedAddress.name }}</text>
              <text class="recipient-phone">{{ selectedAddress.phone }}</text>
              <view class="default-tag" v-if="selectedAddress.isDefault">
                <text class="tag-text">默认</text>
              </view>
            </view>
            <text class="address-detail">{{ selectedAddress.fullAddress }}</text>
          </view>
          <view class="address-icon">
            <text class="icon-location">📍</text>
          </view>
        </view>
        
        <view class="no-address" v-else @click="addAddress">
          <view class="no-address-icon">
            <text class="icon-add">+</text>
          </view>
          <text class="no-address-text">添加收货地址</text>
        </view>
      </view>

      <!-- 商品信息 -->
      <view class="goods-section">
        <view class="section-header">
          <text class="section-title">商品信息</text>
          <text class="goods-count">共{{ totalQuantity }}件</text>
        </view>
        
        <view class="goods-list">
          <view class="goods-item" v-for="item in goodsList" :key="item.id">
            <view class="goods-image">
              <image :src="item.image" mode="aspectFill" class="item-image"></image>
            </view>
            <view class="goods-info">
              <text class="goods-name">{{ item.name }}</text>
              <text class="goods-spec">{{ item.spec }}</text>
              <view class="goods-bottom">
                <text class="goods-price">¥{{ item.price }}</text>
                <text class="goods-quantity">×{{ item.quantity }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 优惠券 - 暂时隐藏，下个版本再开发 -->
      <!-- <view class="coupon-section">
        <view class="section-header" @click="selectCoupon">
          <text class="section-title">优惠券</text>
          <view class="coupon-action">
            <text class="action-text">{{ selectedCoupon ? `已选择 -¥${selectedCoupon.discount}` : '选择优惠券' }}</text>
            <text class="action-arrow">›</text>
          </view>
        </view>
        
        <view class="coupon-card" v-if="selectedCoupon">
          <view class="coupon-info">
            <view class="coupon-amount">
              <text class="amount-symbol">¥</text>
              <text class="amount-value">{{ selectedCoupon.discount }}</text>
            </view>
            <view class="coupon-detail">
              <text class="coupon-name">{{ selectedCoupon.name }}</text>
              <text class="coupon-desc">{{ selectedCoupon.description }}</text>
            </view>
          </view>
          <view class="coupon-tag">
            <text class="tag-text">已选择</text>
          </view>
        </view>
      </view> -->

      <!-- 配送方式 -->
      <view class="delivery-section">
        <view class="section-header">
          <text class="section-title">配送方式</text>
        </view>
        
        <view class="delivery-options">
          <view 
            class="delivery-option" 
            :class="{ 'active': selectedDelivery === option.id }"
            v-for="option in deliveryOptions" 
            :key="option.id"
            @click="selectDelivery(option)"
          >
            <view class="option-info">
              <text class="option-name">{{ option.name }}</text>
              <text class="option-desc">{{ option.description }}</text>
            </view>
            <view class="option-price">
              <text class="price-text">{{ option.price === 0 ? '免费' : `¥${option.price}` }}</text>
            </view>
            <view class="option-radio">
              <view class="radio-inner" v-if="selectedDelivery === option.id"></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 支付方式 -->
      <view class="payment-section">
        <view class="section-header">
          <text class="section-title">支付方式</text>
        </view>
        
        <view class="payment-options">
          <view 
            class="payment-option" 
            :class="{ 'active': selectedPayment === option.id }"
            v-for="option in paymentOptions" 
            :key="option.id"
            @click="selectPayment(option)"
          >
            <view class="option-icon">
              <text class="icon-text">{{ option.icon }}</text>
            </view>
            <view class="option-info">
              <text class="option-name">{{ option.name }}</text>
              <text class="option-desc">{{ option.description }}</text>
            </view>
            <view class="option-radio">
              <view class="radio-inner" v-if="selectedPayment === option.id"></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 订单备注 -->
      <view class="remark-section">
        <view class="section-header">
          <text class="section-title">订单备注</text>
        </view>
        
        <view class="remark-input">
          <textarea 
            v-model="orderRemark" 
            placeholder="选填，请输入您的需求（200字以内）"
            maxlength="200"
            class="remark-textarea"
          ></textarea>
          <text class="char-count">{{ orderRemark.length }}/200</text>
        </view>
      </view>

      <!-- 费用明细 -->
      <view class="cost-section">
        <view class="section-header">
          <text class="section-title">费用明细</text>
        </view>
        
        <view class="cost-details">
          <view class="cost-item">
            <text class="cost-label">商品总价</text>
            <text class="cost-value">¥{{ goodsTotal }}</text>
          </view>
          <view class="cost-item">
            <text class="cost-label">运费</text>
            <text class="cost-value">{{ deliveryFee === 0 ? '免费' : `¥${deliveryFee}` }}</text>
          </view>
          <view class="cost-item" v-if="couponDiscount > 0">
            <text class="cost-label">优惠券</text>
            <text class="cost-value discount">-¥{{ couponDiscount }}</text>
          </view>
          <view class="cost-item total">
            <text class="cost-label">实付款</text>
            <text class="cost-value">¥{{ finalTotal }}</text>
          </view>
        </view>
      </view>

      <!-- 底部占位 -->
      <view class="bottom-placeholder"></view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="total-info">
        <text class="total-label">实付款：</text>
        <text class="total-amount">¥{{ finalTotal }}</text>
      </view>
      <view class="submit-btn" @click="submitOrder">
        <text class="btn-text">提交订单</text>
      </view>
    </view>
    </view>
  </view>
</template>

<script>
import { checkLoginStatus, handleApiError } from '@/utils/loginCheck'
import { getThemeColorFromGlobal, getThemePrimaryColor } from '@/utils/themeUtils'
import PageLoading from '@/components/PageLoading/index.vue'
import pageLoadingMixin from '@/mixins/pageLoading.js'

export default {
  components: {
    PageLoading
  },
  mixins: [pageLoadingMixin],
  data() {
    return {
      // 收货地址
      selectedAddress: {
        id: 1,
        name: '张三',
        phone: '138****8888',
        fullAddress: '北京市朝阳区朝阳路123号院5号楼2单元301室',
        isDefault: true
      },
      
      // 商品列表
      goodsList: [
        {
          id: 1,
          name: '时尚休闲T恤',
          spec: '白色 L码',
          price: '99.00',
          quantity: 1,
          image: '/static/images/product1.jpg'
        },
        {
          id: 2,
          name: '运动鞋',
          spec: '黑色 42码',
          price: '299.00',
          quantity: 1,
          image: '/static/images/product2.jpg'
        }
      ],
      
      // 优惠券
      selectedCoupon: null,
      
      // 配送方式
      selectedDelivery: 1,
      deliveryOptions: [
        {
          id: 1,
          name: '标准配送',
          description: '预计3-5个工作日送达',
          price: 0
        },
        {
          id: 2,
          name: '次日达',
          description: '次日18:00前送达',
          price: 15
        },
        {
          id: 3,
          name: '当日达',
          description: '当日22:00前送达',
          price: 25
        }
      ],
      
      // 支付方式
      selectedPayment: 1,
      paymentOptions: [
        {
          id: 1,
          name: '微信支付',
          description: '推荐使用',
          icon: '💳'
        },
        {
          id: 2,
          name: '支付宝',
          description: '安全便捷',
          icon: '💰'
        },
        {
          id: 3,
          name: '银行卡',
          description: '储蓄卡/信用卡',
          icon: '🏦'
        }
      ],
      
      // 订单备注
      orderRemark: '',
      
      // 主题色
      themeColor: '1'
    }
  },
  
  async onLoad() {
    // 开始页面加载
    this.startPageLoading()
    
    try {
      // 初始化主题色
      await this.initThemeColor()
      this.markThemeLoaded()
      
      // 标记数据已加载
      this.markDataLoaded()
    } catch (error) {
      // console.error('订单确认页面加载失败:', error)
      this.forceCompletePageLoading()
    }
  },
  
  computed: {
    // 动态主题色
    primaryColor() {
      return getThemePrimaryColor(this.themeColor)
    },
    
    // 商品总数量
    totalQuantity() {
      return this.goodsList.reduce((total, item) => total + item.quantity, 0)
    },
    
    // 商品总价
    goodsTotal() {
      return this.goodsList.reduce((total, item) => {
        return total + (parseFloat(item.price) * item.quantity)
      }, 0).toFixed(2)
    },
    
    // 运费
    deliveryFee() {
      const selectedOption = this.deliveryOptions.find(option => option.id === this.selectedDelivery)
      return selectedOption ? selectedOption.price : 0
    },
    
    // 优惠券折扣 - 暂时禁用优惠券功能
    couponDiscount() {
      return 0  // 暂时返回0，下个版本再开发优惠券功能
    },
    
    // 最终总价
    finalTotal() {
      const total = parseFloat(this.goodsTotal) + this.deliveryFee - this.couponDiscount
      return Math.max(0, total).toFixed(2)
    }
  },
  
  onLoad(options) {
    // 接收页面参数
    if (options.goods) {
      try {
        this.goodsList = JSON.parse(decodeURIComponent(options.goods))
      } catch (e) {
        // console.error('解析商品数据失败:', e)
      }
    }
  },
  
  methods: {

    
    // 选择收货地址
    selectAddress() {
      uni.navigateTo({
        url: '/pages/address/index?mode=select'
      })
    },
    
    // 添加收货地址
    addAddress() {
      uni.navigateTo({
        url: '/pages/address/index?mode=add'
      })
    },
    
    // 选择优惠券 - 暂时禁用
    // selectCoupon() {
    //   // 模拟选择优惠券
    //   if (!this.selectedCoupon) {
    //     this.selectedCoupon = {
    //       id: 1,
    //       name: '满减券',
    //       description: '满300减50',
    //       discount: '50.00'
    //     }
    //   } else {
    //     this.selectedCoupon = null
    //   }
    // },
    
    // 选择配送方式
    selectDelivery(option) {
      this.selectedDelivery = option.id
    },
    
    // 选择支付方式
    selectPayment(option) {
      this.selectedPayment = option.id
    },
    
    // 提交订单
    async submitOrder() {
      // 使用统一的登录检测
      const loginResult = await checkLoginStatus()
      if (!loginResult.isLoggedIn) {
        return
      }
      
      if (!this.selectedAddress) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return
      }
      
      if (!this.selectedPayment) {
        uni.showToast({
          title: '请选择支付方式',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({
        title: '检查库存中...'
      })
      
      try {
        // 检查商品库存
        const stockCheckData = this.goodsList.map(item => ({
          skuId: item.skuId,
          quantity: item.quantity
        }))
        
        const stockCheckResponse = await uni.request({
          url: 'http://localhost:8080/app/stock/batchCheck',
          method: 'POST',
          data: stockCheckData,
          header: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          }
        })
        
        if (stockCheckResponse.data.code !== 200) {
          uni.hideLoading()
          uni.showToast({
            title: stockCheckResponse.data.msg || '库存检查失败',
            icon: 'none'
          })
          return
        }
        
        const stockResult = stockCheckResponse.data.data
        if (!stockResult.allAvailable) {
          uni.hideLoading()
          uni.showToast({
            title: stockResult.message || '商品库存不足，请重新选择',
            icon: 'none'
          })
          return
        }
        
        uni.showLoading({
          title: '提交中...'
        })
        
        // 构建订单数据
        const orderData = {
          addressId: this.selectedAddress.id,
          goodsList: this.goodsList,
          couponId: this.selectedCoupon?.id,
          deliveryType: this.selectedDelivery,
          paymentType: this.selectedPayment,
          remark: this.orderRemark,
          goodsTotal: this.goodsTotal,
          deliveryFee: this.deliveryFee,
          couponDiscount: this.couponDiscount,
          finalTotal: this.finalTotal
        }
        
        // 模拟提交订单
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        uni.hideLoading()
        
        uni.showToast({
          title: '订单提交成功',
          icon: 'success'
        })
        
        // 模拟生成订单ID
        const orderId = Date.now()
        
        // 直接跳转到支付页面
        setTimeout(() => {
          uni.redirectTo({
            url: `/pages/payment/index?orderId=${orderId}&amount=${this.finalTotal}&method=${this.selectedPayment}`
          })
        }, 1500)
        
      } catch (error) {
        uni.hideLoading()
        await handleApiError(error)
      }
    },
    
    // 初始化主题色
    async initThemeColor() {
      try {
        this.themeColor = await getThemeColorFromGlobal()
      } catch (error) {
        // console.error('初始化主题色失败:', error)
        this.themeColor = '1' // 默认主题色
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.order-confirm-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 120rpx;
}



// 内容滚动区域
.content-scroll {
  height: 100vh;
  padding-top: 88rpx;
}

// 通用区块样式
.address-section,
.goods-section,
.coupon-section,
.delivery-section,
.payment-section,
.remark-section,
.cost-section {
  margin: 20rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(59, 130, 246, 0.06);
  border: 1rpx solid rgba(59, 130, 246, 0.08);
  overflow: hidden;
}

// 区块头部
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid rgba(59, 130, 246, 0.08);
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #1f2937;
  }
  
  .goods-count {
    font-size: 26rpx;
    color: #6b7280;
  }
}

// 收货地址
.address-action,
.coupon-action {
  display: flex;
  align-items: center;
  
  .action-text {
    font-size: 26rpx;
    color: #3B82F6;
    margin-right: 8rpx;
  }
  
  .action-arrow {
    font-size: 24rpx;
    color: #3B82F6;
  }
}

.address-card {
  display: flex;
  align-items: center;
  padding: 30rpx;
  
  .address-info {
    flex: 1;
    
    .address-header {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      
      .recipient-name {
        font-size: 30rpx;
        font-weight: 600;
        color: #1f2937;
        margin-right: 20rpx;
      }
      
      .recipient-phone {
        font-size: 26rpx;
        color: #6b7280;
        margin-right: 20rpx;
      }
      
      .default-tag {
        background: linear-gradient(135deg, #3B82F6 0%, #60A5FA 100%);
        padding: 4rpx 12rpx;
        border-radius: 8rpx;
        
        .tag-text {
          font-size: 20rpx;
          color: #fff;
        }
      }
    }
    
    .address-detail {
      font-size: 26rpx;
      color: #6b7280;
      line-height: 1.5;
    }
  }
  
  .address-icon {
    .icon-location {
      font-size: 40rpx;
    }
  }
}

.no-address {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 30rpx;
  
  .no-address-icon {
    width: 80rpx;
    height: 80rpx;
    background: rgba(59, 130, 246, 0.08);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20rpx;
    
    .icon-add {
      font-size: 36rpx;
      color: #3B82F6;
    }
  }
  
  .no-address-text {
    font-size: 26rpx;
    color: #6b7280;
  }
}

// 商品列表
.goods-list {
  padding: 0 30rpx 30rpx;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid rgba(59, 130, 246, 0.08);
  
  &:last-child {
    border-bottom: none;
  }
  
  .goods-image {
    width: 120rpx;
    height: 120rpx;
    margin-right: 20rpx;
    
    .item-image {
      width: 100%;
      height: 100%;
      border-radius: 12rpx;
    }
  }
  
  .goods-info {
    flex: 1;
    
    .goods-name {
      font-size: 28rpx;
      font-weight: 500;
      color: #1f2937;
      margin-bottom: 8rpx;
      display: block;
    }
    
    .goods-spec {
      font-size: 24rpx;
      color: #6b7280;
      margin-bottom: 16rpx;
      display: block;
    }
    
    .goods-bottom {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .goods-price {
        font-size: 28rpx;
        font-weight: 600;
        color: #3B82F6;
      }
      
      .goods-quantity {
        font-size: 24rpx;
        color: #6b7280;
      }
    }
  }
}

// 优惠券
.coupon-card {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background: rgba(59, 130, 246, 0.04);
  
  .coupon-info {
    flex: 1;
    display: flex;
    align-items: center;
    
    .coupon-amount {
      display: flex;
      align-items: baseline;
      margin-right: 30rpx;
      
      .amount-symbol {
        font-size: 24rpx;
        color: #3B82F6;
        font-weight: 600;
      }
      
      .amount-value {
        font-size: 36rpx;
        color: #3B82F6;
        font-weight: bold;
      }
    }
    
    .coupon-detail {
      .coupon-name {
        font-size: 28rpx;
        font-weight: 600;
        color: #1f2937;
        margin-bottom: 4rpx;
        display: block;
      }
      
      .coupon-desc {
        font-size: 24rpx;
        color: #6b7280;
        display: block;
      }
    }
  }
  
  .coupon-tag {
    background: linear-gradient(135deg, #3B82F6 0%, #60A5FA 100%);
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
    
    .tag-text {
      font-size: 22rpx;
      color: #fff;
    }
  }
}

// 配送和支付选项
.delivery-options,
.payment-options {
  padding: 0 30rpx 30rpx;
}

.delivery-option,
.payment-option {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid rgba(59, 130, 246, 0.08);
  transition: all 0.3s ease;
  
  &:last-child {
    border-bottom: none;
  }
  
  &.active {
    background: rgba(59, 130, 246, 0.04);
    border-radius: 12rpx;
    margin: 0 -20rpx;
    padding: 24rpx 20rpx;
  }
  
  .option-icon {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
    
    .icon-text {
      font-size: 32rpx;
    }
  }
  
  .option-info {
    flex: 1;
    
    .option-name {
      font-size: 28rpx;
      font-weight: 500;
      color: #1f2937;
      margin-bottom: 4rpx;
      display: block;
    }
    
    .option-desc {
      font-size: 24rpx;
      color: #6b7280;
      display: block;
    }
  }
  
  .option-price {
    margin-right: 20rpx;
    
    .price-text {
      font-size: 26rpx;
      font-weight: 600;
      color: #3B82F6;
    }
  }
  
  .option-radio {
    width: 36rpx;
    height: 36rpx;
    border: 2rpx solid #d1d5db;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    
    .radio-inner {
      width: 20rpx;
      height: 20rpx;
      background: #3B82F6;
      border-radius: 50%;
    }
  }
  
  &.active .option-radio {
    border-color: #3B82F6;
  }
}

// 订单备注
.remark-input {
  padding: 30rpx;
  position: relative;
  
  .remark-textarea {
    width: 100%;
    min-height: 120rpx;
    padding: 20rpx;
    border: 1rpx solid rgba(59, 130, 246, 0.08);
    border-radius: 12rpx;
    font-size: 26rpx;
    color: #1f2937;
    background: #fff;
    resize: none;
    
    &::placeholder {
      color: #9ca3af;
    }
  }
  
  .char-count {
    position: absolute;
    bottom: 40rpx;
    right: 50rpx;
    font-size: 22rpx;
    color: #9ca3af;
  }
}

// 费用明细
.cost-details {
  padding: 0 30rpx 30rpx;
}

.cost-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 0;
  
  &.total {
    border-top: 1rpx solid rgba(59, 130, 246, 0.08);
    padding-top: 24rpx;
    margin-top: 16rpx;
    
    .cost-label,
    .cost-value {
      font-size: 30rpx;
      font-weight: 600;
    }
  }
  
  .cost-label {
    font-size: 26rpx;
    color: #6b7280;
  }
  
  .cost-value {
    font-size: 26rpx;
    color: #1f2937;
    font-weight: 500;
    
    &.discount {
      color: #3B82F6;
    }
  }
}

// 底部占位
.bottom-placeholder {
  height: 120rpx;
}

// 底部操作栏
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  border-top: 1rpx solid rgba(59, 130, 246, 0.08);
  box-shadow: 0 -4rpx 20rpx rgba(59, 130, 246, 0.06);
  
  .total-info {
    flex: 1;
    
    .total-label {
      font-size: 26rpx;
      color: #6b7280;
    }
    
    .total-amount {
      font-size: 36rpx;
      font-weight: bold;
      color: #3B82F6;
    }
  }
  
  .submit-btn {
    width: 240rpx;
    height: 80rpx;
    background: linear-gradient(135deg, #3B82F6 0%, #60A5FA 100%);
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 12rpx rgba(59, 130, 246, 0.3);
    transition: all 0.3s ease;
    
    &:active {
      transform: scale(0.98);
    }
    
    .btn-text {
      font-size: 28rpx;
      font-weight: 600;
      color: #fff;
    }
  }
}
</style>